<template>
  <div id="change-credit">
    <div class="gathering">收款性质：<span>个人</span></div>
    <group>
      <x-input title="收款人姓名:" v-model="namevalue" ref="name01" name="username" is-type="china-name"></x-input>
      <popup-picker :title="'银行名称:'" placeholder="请选择银行" value-text-align="left" :data="list01" v-model="bankvalue" @on-show="onShow" @on-hide="onHide" @on-change="onChange" ></popup-picker>
      <x-input title="开户行全称:" v-model="allvalue" type="text" placeholder="请输入开户行全称" ></x-input>
      <x-address title="开户银行省市:" placeholder="请选择开户银行省市" value-text-align="left"  v-model="cityvalue" :list="addressData" hide-district></x-address>
      <x-input title="收款银行账号:" v-model="accountvalue" type="text" placeholder="请输入收款银行账号" ></x-input>
      <x-input title="收款人身份证:" v-model="cardvalue" type="text" placeholder="请正确填写身份证号" ></x-input>
    </group>
    <h4>上传身份证</h4>
    <div class="uploading-file">
      <div class="person-img" @click="wxChooseImage">
        <img v-if="imgipcard" :src="imgipcard" class="identity-card" />
        <div  class="img-choose" v-else>
          <img src="../../static/img/issue.png" />
        </div>
      </div>
      <p>需上传个人清晰身份证</p>
    </div>
    <x-dialog v-model="showHideOnBlur" class="dialog-demo image-code credit-vcode" hide-on-blur>
      <x-input :show-clear="false" placeholder="请输入图形验证码" v-model="imageCode" class="weui-cell_vcode ">
        <img slot="label" src="../../static/img/mima@2x.png" >
        <img slot="right" @click="imgevent" class="weui-vcode-img" :src="urlImgCode + captchaid">
      </x-input>
      <x-input  ref="code01" :show-clear="false" v-model="codeval" keyboard="number" class="weui-vcode" placeholder="请输入短信验证码">
        <img slot="label" src="../../static/img/mima@2x.png" >
        <div slot="right" v-bind:class="[start? 'vcode-inactive':'vcode-active']" @click="sendcode" style="color:rgb(47, 120, 236)">{{timerText()}}</div>
        <countdown style="display:none" slot="right" :start="start" @on-finish="timerFinished" v-model="timer"></countdown>
      </x-input>
      <div @click="confirmImgCode" class="confirm">
        <span>确定</span>
      </div>
    </x-dialog>
    <div class="credit-btn">
      <flexbox>
        <flexbox-item>
          <x-button type="primary" @click.native="confirm">确定</x-button>
        </flexbox-item>
        <flexbox-item>
          <x-button type="warn" @click.native="reset">重置</x-button>
        </flexbox-item>
      </flexbox>
    </div>
  </div>
</template>
<script>
var timeStamp = String(Number(new Date()))
import { XInput, Group, PopupPicker, XAddress, ChinaAddressV4Data, Flexbox, FlexboxItem, XButton, Value2nameFilter as value2name, TransferDomDirective as TransferDom, XDialog, Countdown } from 'vux'
import api from '../api'
import utils from '../utils'
export default {
  directives: {
    TransferDom
  },
  data () {
    return {
      banklist: [],
      list01: [],
      namevalue: '',
      allvalue: '',
      bankvalue: [],
      cityvalue: [],
      accountvalue: '',
      cardvalue: '',
      bankcode: '',
      imgipcard: '',
      codeval: '',
      addressData: ChinaAddressV4Data,
      tokenval: '',
      mobile: '',
      timer: 60,
      start: false,
      showHideOnBlur: false,
      imageCode: '', // 图片验证码
      urlImgCode: this.$store.state.imgvcode,
      captchaid: ''
    }
  },
  components: {
    XInput,
    Group,
    PopupPicker,
    XAddress,
    Flexbox,
    FlexboxItem,
    XButton,
    Countdown,
    XDialog
  },
  created () {
    var cityinit = []
    var provinceinit = [], List = []
    window.document.title = '绑卡'
    api.bank().then(res => {
      this.banklist = res.data.list
      for (var i in this.banklist) {
        List.push(this.banklist[i].bankName)
      }
      this.list01.push(List)
    })
    this.tokenval = utils.AuthToken(timeStamp, this.$store.state.userkey)
    var params = {
      Tokenuser: this.tokenval,
      userid: this.$store.state.userID,
      timestamp: timeStamp
    }
    api.message(params).then(res => {
      this.mobile = res.data.mobile
    })
    api.accountmessage(params).then(res => {
      console.log(res)
      if (res.status === '200') {
        if (res.data.bankName) {
          this.bankvalue.push(res.data.bankName)
        }
        this.namevalue = res.data.realName
        this.allvalue = res.data.bankBranch
        this.bankcode = res.data.bankCode
        if (res.data.cardCity && res.data.cardProvince) {
          if (res.data.cardCity === res.data.cardProvince) {
            provinceinit.push(res.data.cardProvince)
            if (provinceinit[0].indexOf('市') > -1) {
              this.cityvalue.push(res.data.cardProvince)
              this.cityvalue.push('市辖区')
            } else {
              this.cityvalue.push(res.data.cardProvince + '市')
              this.cityvalue.push('市辖区')
            }
          } else {
            cityinit.push(res.data.cardCity)
            provinceinit.push(res.data.cardProvince)
            provinceinit = provinceinit.concat(cityinit)
            this.cityvalue = provinceinit
          }
        } else if (res.data.cardCity && !res.data.cardProvince) {
          this.cityvalue.push(res.data.cardCity)
          cityinit.push('市辖区')
          this.cityvalue = this.cityvalue.concat(cityinit)
        } else if (res.data.cardProvince && !res.data.cardCity) {
          this.cityvalue.push(res.data.cardProvince)
          cityinit.push('市辖区')
          this.cityvalue = this.cityvalue.concat(cityinit)
        }
        this.accountvalue = res.data.bankCard
        this.cardvalue = res.data.idCard
        if (res.data.idCardPicUrl) {
          this.imgipcard = res.data.idCardPicUrl
        } else {
          this.imgipcard = ''
        }
      }
    })
    utils.jssdkwx(api, this.$wechat, this.$store)
  },
  methods: {
     /* JSSDK 图片操作 */
    wxChooseImage: function () { // 图片选取
      var self = this
      this.$wechat.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: self.wxUploadImage
      })
    },
    wxUploadImage: function (res) { // 图片上传
      var self = this
      var localIds = res.localIds.toString()
      this.$wechat.uploadImage({
        localId: localIds.toString(),
        isShowProgressTips: 1, // 默认为1，显示进度提示
        success: self.downloadImage
      })
    },
    downloadImage: function (res) {
      var timeStamp = String(parseInt(Number(new Date()) / 1000))
      var tokenval = utils.AuthToken(timeStamp, this.$store.state.userkey)
      var self = this
      var serverId = res.serverId // 返回图片的服务器端ID
      this.$vux.loading.show({text: '图片上传中'})
      var params = {
        token: tokenval,
        timestamp: timeStamp,
        userId: self.$store.state.userID,
        imageType: 3,
        wexinMediaId: serverId
      }
      api.upload(params).then(res => {
        if (res.status === '200') {
          self.$vux.loading.hide()
          self.imgipcard = res.data.imageUrl
        } else {
          this.$vux.toast.show({
            text: res.message,
            type: 'warn',
            width: '4rem'
          })
        }
      })
    },
    onChange (val) {
      for (var b in this.banklist) {
        if (this.banklist[b].bankName === val[0]) {
          this.bankcode = this.banklist[b].bankCode
        }
      }
    },
    onShow () {
      console.log('on show')
    },
    onHide (type) {
      console.log('on hide', type)
    },
    sendcode () {
      var tokenVal = utils.AnonToken(timeStamp)
      if (this.imageCode === '') {
        this.$vux.toast.show({
          text: '请输入图形验证码',
          type: 'warn',
          width: '4rem'
        })
      } else if (this.start) {
        return
      } else {
        var params = {
          captcha: this.imageCode,
          captchaId: this.captchaid
        }
        var self = this
        api.validcode(params).then(res => {
          if (res.status === '200') {
            this.start = true
            api.sendCode({
              token: tokenVal,
              timestamp: timeStamp,
              mobile: self.mobile,
              type: 1,
              sendType: 7,
              from: 0,
              captcha: self.imageCode,
              captchaId: self.captchaid
            }).then(res => {
              console.log(res)
              if (res.status === '200') {
                self.$vux.toast.show({
                  text: res.message,
                  type: 'success',
                  width: '4rem'
                })
              } else {
                self.$vux.toast.show({
                  text: res.message,
                  type: 'warn',
                  width: '4rem'
                })
              }
            })
          } else {
            this.$vux.toast.show({
              text: '输入错误，请重新输入',
              type: 'warn',
              width: '4rem'
            })
          }
        })
      }
    },
    imgevent () {
      this.captchaid = '00' + utils.randomString(32)
    },
    confirmImgCode () {
      var tokenVal = utils.AnonToken(timeStamp)
      var self = this
      if (this.imageCode === '') {
        this.$vux.toast.show({
          text: '请输入图形验证码',
          type: 'warn',
          width: '4rem'
        })
      } else if (this.codeval === '') {
        this.$vux.toast.show({
          text: '请输入短信验证码',
          type: 'warn',
          width: '4rem'
        })
      } else {
        api.validate({
          token: tokenVal,
          timestamp: timeStamp,
          mobile: self.mobile,
          type: 1,
          sendType: 7,
          vcode: self.codeval,
          from: 0,
          captcha: self.imageCode,
          captchaId: self.captchaid
        }).then(res => {
          console.log(res)
          if (res.status === '200') {
            self.showHideOnBlur = false
            self.soultButton()
          } else {
            self.$vux.toast.show({
              text: res.message,
              type: 'warn',
              width: '4rem'
            })
            self.captchaid = '00' + utils.randomString(32)
          }
        })
      }
    },
    // 确定
    confirm () {
      if (this.namevalue === '') {
        this.$vux.toast.show({
          text: '请填写姓名',
          type: 'warn',
          width: '4rem'
        })
      } else if (this.$refs.name01.valid === false) {
        this.$vux.toast.show({
          text: '名字格式不正确',
          type: 'warn',
          width: '4rem'
        })
      } else if (this.bankvalue.length === 0) {
        this.$vux.toast.show({
          text: '请选择银行',
          type: 'warn',
          width: '4rem'
        })
      } else if (this.allvalue === '') {
        this.$vux.toast.show({
          text: '请输入开户行全称',
          type: 'warn',
          width: '4rem'
        })
      } else if (this.cityvalue.length === 0) {
        this.$vux.toast.show({
          text: '请选择开户行省市',
          type: 'warn',
          width: '4rem'
        })
      } else if (this.accountvalue === '') {
        this.$vux.toast.show({
          text: '请输入收款银行账号',
          type: 'warn',
          width: '4rem'
        })
      } else if (this.cardvalue === '') {
        this.$vux.toast.show({
          text: '请填写收款人身份证号',
          type: 'warn',
          width: '4rem'
        })
      } else if (utils.ipcard(this.cardvalue) !== true) {
        var self = this
        this.$vux.toast.show({
          text: utils.ipcard(self.cardvalue),
          type: 'warn',
          width: '4rem'
        })
      } else if (this.imgipcard === '') {
        this.$vux.toast.show({
          text: '请上传个人身份证',
          type: 'warn',
          width: '4rem'
        })
      } else {
        this.showHideOnBlur = !this.showHideOnBlur
        this.imageCode = ''
        this.codeval = ''
        this.captchaid = '00' + utils.randomString(32)
      }
    },
    soultButton () {
      var address = value2name(this.cityvalue, ChinaAddressV4Data).split(' ')
      var citys = address[1]
      if (citys === '市辖区') {
        citys = address[0]
      } else {
        citys = address[1]
      }
      api.bind({
        token: this.tokenval,
        timestamp: timeStamp,
        bankCode: this.bankcode,
        bankCard: this.accountvalue,
        bankName: this.bankvalue[0],
        userId: this.$store.state.userID,
        idCard: this.cardvalue,
        realName: this.namevalue,
        bankBranch: this.allvalue,
        cardProvince: address[0],
        cardCity: citys,
        idCardPicUrl: this.imgipcard,
        vcode: this.codeval
      }).then(res => {
        if (res.status === '200') {
          this.$vux.toast.show({
            text: '绑定成功',
            type: 'success',
            width: '4rem'
          })
          setTimeout(() => {
            window.location.href = '/setting/card'
          }, 2000)
        } else {
          this.$vux.toast.show({
            text: res.message,
            type: 'warn',
            width: '4rem'
          })
        }
      })
    },
    // 重置
    reset () {
      this.namevalue = ''
      this.bankvalue = []
      this.cityvalue = []
      this.allvalue = ''
      this.accountvalue = ''
      this.cardvalue = ''
      this.imgipcard = ''
    },
    timerFinished: function () {
      this.start = false
      this.timer = 60
    },
    timerText: function () {
      if (this.start) {
        return '重新发送(' + this.timer + ')'
      } else {
        return '发送验证码'
      }
    }
  }
}
</script>

